package com.xm.dao.reception_desk;

import com.xm.entity.Address;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 收货地址Dao层
 *
 * @author 康文程
 * @date 2024-1-7 下午 01:22
 */
public class AddressDao extends BaseUtil {
    /**
     * 获取用户所有收货地址
     *
     * @param informationId 账号信息Id
     * @return 收货地址列表
     * @throws SqlErrorException SQL执行异常
     */
    public List<Address> getAllAddresses(Integer informationId) throws SqlErrorException {
        @Language("sql")
        String sql = "SELECT * FROM address WHERE information_id = ?";
        ResultSet resultSet = executeQuery(sql, informationId);

        List<Address> addressList = new ArrayList<>();
        try {
            while (resultSet.next()) {
                Address address = getAddressFromResultSet(resultSet);
                addressList.add(address);
            }
        } catch (SQLException e) {
            throw new SqlErrorException("查询失败", e);
        } finally {
            close(resultSet);
        }

        return addressList;
    }

    /**
     * 根据用户信息表ID查询收货地址
     *
     * @param addressId 收货地址Id
     * @return 收货地址实体类
     * @throws SqlErrorException SQL执行异常
     */
    public Address getAddressByInformationId(Integer addressId) throws SqlErrorException {
        @Language("sql")
        String sql = "SELECT * FROM address WHERE address_id = ? LIMIT 1";
        ResultSet resultSet = executeQuery(sql, addressId);

        Address address = null;
        try {
            if (resultSet.next()) {
                address = getAddressFromResultSet(resultSet);
            }
        } catch (SQLException e) {
            throw new SqlErrorException("查询失败", e);
        } finally {
            close(resultSet);
        }

        return address;
    }

    /**
     * 删除收货地址
     * @param addressId 收货地址Id
     * @return 收货地址实体类
     * @throws SqlErrorException SQL执行异常
     */
    public boolean getAddressDelete(Integer addressId) throws SqlErrorException {
        @Language("sql")
        String sql = "DELETE FROM address WHERE address_id = ?";
        Object[] params = {addressId};
        int result = executeUpdate(sql, params);
        return result == 1;
    }

    /**
     * 添加或修改收货地址
     * 如果传了getAddressId则修改没有则新增
     *
     * @param address 收货地址实体类
     * @throws SqlErrorException SQL执行异常
     */
    public boolean saveOrUpdateAddress(Address address) throws SqlErrorException {
        if (address.getAddressId() == null) {
            // 添加收货地址
            @Language("sql")
            String sql = "INSERT INTO address (address_name, address_phone, address_province, address_city, address_district, full_address, address_labels, is_selected_address, information_id , longitude , latitude) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)";
            int id = executeUpdate(sql, address.getAddressName(), address.getAddressPhone(), address.getAddressProvince(), address.getAddressCity(), address.getAddressDistrict(), address.getFullAddress(), address.getAddressLabels(), 1, address.getInformationId(),address.getLongitude(),address.getLatitude());
            return id != 0;
        } else {
            // 修改收货地址
            @Language("sql")
            String sql = "UPDATE address SET address_name = ?, address_phone = ?, address_province = ?, address_city = ?, address_district = ?, full_address = ?, address_labels = ? , longitude = ? , latitude = ? WHERE address_id = ?";
            int id = executeUpdate(sql, address.getAddressName(), address.getAddressPhone(), address.getAddressProvince(), address.getAddressCity(), address.getAddressDistrict(), address.getFullAddress(), address.getAddressLabels(),address.getLongitude(),address.getLatitude(), address.getAddressId());
            return id != 0;
        }
    }
    /**
     * 根据收货地址ID修改 is_selected_address
     *
     * @param addressId         收货地址ID（如果为空则修改全部）
     * @param isSelectedAddress 是否选中收货地址（0-未选中，1-选中）
     * @return 是否成功修改
     * @throws SqlErrorException SQL执行异常
     */
    public boolean updateIsSelectedAddress(String addressId, Integer isSelectedAddress) throws SqlErrorException {
        @Language("sql")
        String sql;
        if ("".equals(addressId)){
            addressId = null;
        }
        if (addressId == null) {
            // 如果地址ID为空，则更新全部记录
            sql = "UPDATE address SET is_selected_address = ?";
            int rowsAffected = executeUpdate(sql, isSelectedAddress);
            return rowsAffected != 0;
        } else {
            // 否则只更新指定ID的记录
            sql = "UPDATE address SET is_selected_address = ? WHERE address_id = ?";
            int rowsAffected = executeUpdate(sql, isSelectedAddress, Integer.parseInt(addressId));
            return rowsAffected != 0;
        }
    }
    /**
     * 根据信息ID和选中状态查询被选中收货地址
     *
     * @param informationId      信息ID
     * @return 收货地址列表
     * @throws SqlErrorException SQL执行异常
     */
    public Address getAddressesByInformationIdAndSelected(Integer informationId) throws SqlErrorException {
        @Language("sql")
        String sql = "SELECT * FROM address WHERE information_id = ? AND is_selected_address = 0";
        ResultSet resultSet = executeQuery(sql, informationId);
        Address address = null;
        try {
            while (resultSet.next()) {
                address = getAddressFromResultSet(resultSet);
            }
        } catch (SQLException e) {
            throw new SqlErrorException("查询失败", e);
        } finally {
            close(resultSet);
        }
        return address;
    }

    private Address getAddressFromResultSet(ResultSet resultSet) throws SQLException {
        Address address = new Address();
        address.setAddressId(resultSet.getInt("address_id"));
        address.setAddressName(resultSet.getString("address_name"));
        address.setAddressPhone(resultSet.getString("address_phone"));
        address.setAddressProvince(resultSet.getString("address_province"));
        address.setAddressCity(resultSet.getString("address_city"));
        address.setAddressDistrict(resultSet.getString("address_district"));
        address.setFullAddress(resultSet.getString("full_address"));
        address.setAddressLabels(resultSet.getString("address_labels"));
        address.setIsSelectedAddress(resultSet.getInt("is_selected_address"));
        address.setInformationId(resultSet.getInt("information_id"));
        address.setLatitude(resultSet.getString("latitude"));
        address.setLongitude(resultSet.getString("longitude"));
        return address;
    }
}
